using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.UI;
using System.Xml;
using System.Xml.Schema;
using Dzzzr;

namespace MonitoringService
{
  public partial class KML : Page
  {
    private string login = null;
    private string password = null;

    protected void Page_Load(object sender, EventArgs e)
    {
      login = Request.Params["login"];
      password = Request.Params["password"];
      DzzzrPointingService pointingService =  new DzzzrPointingService();
      //pointingService.Url = ConfigurationManager.AppSettings["PointingService"];
      List<SimpleMarker> markers = pointingService.GetMarkers("game1",/*"sa","sa*/login,password);
      if (markers.Count > 0)
      {
        XmlDocument kml = CreateKML(markers);
        Response.ContentType = "application/octet-stream";///*"text/xml";//*/ "application/vnd.google-earth.kml+xml";
        //Response.AddHeader("Content-Disposition", "attachment; filename=kml.kml");

        Response.Clear();
        Response.Write(kml.InnerXml);
        //Response.WriteFile(Request.MapPath("SamplesInMaps.kml"));
        Response.Flush();
        Response.Close();
        Response.End();
      }
    }

    private XmlDocument CreateKML(List<SimpleMarker> markers)
    {
      XmlDocument kml = new XmlDocument();
      string startXML =
        @"<?xml version=""1.0"" encoding=""UTF-8""?>
      <kml xmlns=""http://earth.google.com/kml/2.1""><Document/></kml>";
      kml.LoadXml(startXML);
      foreach (SimpleMarker marker in markers)
      {
        XmlNode document = kml.DocumentElement.ChildNodes[0];
        XmlNode placemark = document.AppendChild(kml.CreateElement("Placemark"));
        XmlNode name = placemark.AppendChild(kml.CreateElement("name"));
        name.InnerText = marker.MarkerName;
        XmlNode point = placemark.AppendChild(kml.CreateElement("Point"));
        XmlNode coordinates = point.AppendChild(kml.CreateElement("coordinates"));
        coordinates.InnerText = String.Format("{0},{1},0", marker.Longitude, marker.Latitude);
      }
      return kml;
    }
  }
}